package ren.kane.phoenix.util.io;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author renrk(1275) on 2019-08-05 5:04 PM
 **/
public class BufferedInputStreamTest {

    private static final int LEN = 5;

    private static void testBufferedInputStream() {
        try {
            // 创建BufferedInputStream字节流，内容是ArrayLetters数组
            File file = new File("dir", "file.txt");
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file), 512);
            // 从字节流中读取5个字节。“abcde”，a对应0x61，b对应0x62，依次类推...
            for (int i = 0; i < LEN; i++) {
                if (inputStream.available() >= 0) {
                    int tmp = inputStream.read();
                    System.out.printf("%d : 0x%s\n", i, Integer.toHexString(tmp));
                }
            }
            // 若“该字节流”不支持标记功能，则直接退出
            if (!inputStream.markSupported()) {
                System.out.println("make not supported!");
                return;
            }
            // 标记“当前索引位置”，即标记第6个位置的元素“f”
            inputStream.mark(1024);
            inputStream.skip(22);
            // 读取5个字节
            byte[] buf = new byte[LEN];
            inputStream.read(buf, 0, LEN);
            String str1 = new String(buf);
            System.out.printf("str1=%s\n", str1);
            // 重置“输入流的索引”为mark()所标记的位置，即重置到“f”处
            inputStream.reset();
            // 从“重置后的字节流”中读取5个字节到buf中。即读取“fghij”
            inputStream.read(buf, 0, LEN);
            String str2 = new String(buf);
            System.out.printf("str2=%s\n", str2);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testBufferedInputStream();
    }
}
